// 仿后端数据
const courseData = [
  {
    courseId: "0",
    isSelected: false,
    coverImage:
      "https://cdn3.axureshop.com/demo/2080033/images/%E5%9F%B9%E8%AE%AD%E8%AE%A1%E5%88%92%E8%AF%A6%E6%83%85/u13641.png",
    courseTitle: "2022新员工入职",
    courseType: "视频",
    courseVideo: "../resource-lxr/courseVideo1.mp4",
    courseMaterial: "",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 11,
    releaseDate: "2022-01-03",
    releaseTime: "",
    isInstantRelease: false,
    updateDate: "2022-01-04",
    courseIntro: "欢迎参加2022新员工入职培训！",
  },
  {
    courseId: "1",
    isSelected: false,
    coverImage: "../resource-lxr/images/04.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseVideo:
      "https://v.gbimg.cn/20220705/7decdc8e41f206732cf1b31da03f2cb8/main_1.mp4",
    courseCategory: "入职培训",
    visibleRange: "全部成员",
    numOfStudents: 12,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "2",
    isSelected: false,
    coverImage: "../resource-lxr/images/01.png",
    courseTitle: "2022办公技能培训",
    courseType: "视频",
    courseCategory: "办公技能培训",
    visibleRange: "指定成员",
    numOfStudents: 13,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "3",
    isSelected: false,
    coverImage: "../resource-lxr/images/02.png",
    courseTitle: "PPT培训",
    courseType: "视频",
    courseCategory: "办公技能培训",
    visibleRange: "指定成员",
    numOfStudents: 14,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "4",
    isSelected: false,
    coverImage: "../resource-lxr/images/03.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 15,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "5",
    isSelected: false,
    coverImage: "../resource-lxr/images/05.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 16,
    releaseDate: "2021-01-03",
    updateDate: "2021-01-04",
  },
  {
    courseId: "6",
    isSelected: false,
    coverImage: "../resource-lxr/images/06.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 17,
    releaseDate: "2022-09-01",
    updateDate: "2022-09-04",
  },
  {
    courseId: "7",
    isSelected: false,
    coverImage: "../resource-lxr/images/01.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 18,
    releaseDate: "2022-08-03",
    updateDate: "2022-08-04",
  },
  {
    courseId: "8",
    isSelected: false,
    coverImage: "../resource-lxr/images/02.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 19,
    releaseDate: "2021-08-03",
    updateDate: "2021-08-04",
  },
  {
    courseId: "9",
    isSelected: false,
    coverImage: "../resource-lxr/images/03.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 20,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "10",
    isSelected: false,
    coverImage: "../resource-lxr/images/04.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 21,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "11",
    isSelected: false,
    coverImage: "../resource-lxr/images/05.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 22,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "12",
    isSelected: false,
    coverImage: "../resource-lxr/images/06.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 23,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "13",
    isSelected: false,
    coverImage: "../resource-lxr/images/01.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 24,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "14",
    isSelected: false,
    coverImage: "../resource-lxr/images/02.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 25,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "15",
    isSelected: false,
    coverImage: "../resource-lxr/images/03.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 26,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "16",
    isSelected: false,
    coverImage: "../resource-lxr/images/02.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 27,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "17",
    isSelected: false,
    coverImage: "../resource-lxr/images/03.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 28,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "18",
    isSelected: false,
    coverImage: "../resource-lxr/images/04.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 29,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "19",
    isSelected: false,
    coverImage: "../resource-lxr/images/05.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 30,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
  {
    courseId: "20",
    isSelected: false,
    coverImage: "../resource-lxr/images/06.png",
    courseTitle: "2021新员工入职",
    courseType: "视频",
    courseCategory: "入职培训",
    visibleRange: "指定成员",
    numOfStudents: 31,
    releaseDate: "2022-01-03",
    updateDate: "2022-01-04",
  },
];
// 表单验证规则
const rules = {
  // 必填
  courseTitle: {
    tips: "请输入课程名称",
    contentReg: /^\s*$/,
    contentErrorMessage: "请输入课程名称",
    sizeReg: "",
    sizeErrorMessage: "",
  },
  // 必填
  coverImage: {
    tips: "请上传文件：支持png、jpg、jpeg等格式；大小不超过10mb",
    contentReg: /^(\s|\S)+(jpg|jpeg|png|JPG|PNG|JPEG)+$/,
    contentErrorMessage: "请检查文件格式是否为：png、jpg、jpeg等",
    sizeReg: /[\u4e00-\u9fa5]{2,}/,
    sizeErrorMessage: "文件大小不超过10mb",
  },
  // 必填
  courseCategory: {
    tips: "请选择课程分类",
    contentReg: /^\s*$/,
    contentErrorMessage: "请选择课程分类",
    sizeReg: "",
    sizeErrorMessage: "",
  },
  // 必填
  courseVideo: {
    tips: "请上传文件：支持mp4、m4v、aiv等格式；大小不超过10G",
    contentReg: /^(\s|\S)+(mp4|MP4|m4v|M4V|aiv|AIV)+$/,
    contentErrorMessage: "请检查文件格式是否为：mp4、m4v、aiv等",
    sizeReg: /[\u4e00-\u9fa5]{2,}/,
    sizeErrorMessage: "文件大小不超过10mb",
  },
  // 选填
  courseMaterial: {
    tips: "· 支持pdf、doc、docx、exl格式；大小不超过100mb",
    contentReg: /^(\s|\S)+(pdf|PDF|doc|DOC|docx|DOCX|exl|EXL)+$/,
    contentErrorMessage: "请检查文件格式是否为：pdf、doc、docx、exl等",
    sizeReg: /[\u4e00-\u9fa5]{2,}/,
    sizeErrorMessage: "文件大小不超过10mb",
  },
};
// 创建课程id
let index = 100;
function createId() {
  return ++index;
}
// const pageSize = 10;

// 1. 渲染表格
renderTable(courseData);
// 2. 渲染分页

// 渲染表格函数
function renderTable(data, currentPage = 1) {
  const pageSize = parseInt($(".per-page").val());
  $(".box-body>table>tbody").empty();
  renderPage(data, currentPage);
  const startIndex = (currentPage - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const pageData = data.slice(startIndex, endIndex);
  for (let i = 0; i < pageData.length; ++i) {
    const checked = pageData[i].isSelected ? "checked" : "";
    $(".box-body>table>tbody").append(`
        <tr data-id="${pageData[i].courseId}">
            <td><input ${checked} class="select-box" type="checkbox"/></td>     
            <td><img class="coverImg" src="${pageData[i].coverImage}"/></td>
            <td>${pageData[i].courseTitle}</td>
            <td>${pageData[i].courseType}</td>
            <td>${pageData[i].courseCategory}</td>
            <td>${pageData[i].visibleRange}</td>
            <td>${pageData[i].numOfStudents}</td>
            <td>${pageData[i].releaseDate}</td>
            <td>${pageData[i].updateDate}</td>
            <td>
            <button 
            class="btn btn-primary btn-lg edit" 
            data-toggle="modal" 
            data-target="#editModal"
            id="${pageData[i].courseId}" >编辑</button>
            <button type="button" 
            class="btn btn-link btn-lg del" 
            data-toggle="modal" 
            data-target="#delModal"
            id="${pageData[i].courseId}">删除</button>            
            </td>
        </tr>`);
  }
}
// 单独渲染一个模态框

// 渲染分页
function renderPage(data, currentPage = 1) {
  const pageSize = parseInt($(".per-page").val());
  $(".pagination").empty();
  const totalPages = Math.ceil(data.length / pageSize);
  $(".page>.pagination").append(`<li><a href="#" class="pre">&laquo;</a></li>`);
  for (let i = 0; i < totalPages; ++i) {
    $(".page>.pagination").append(`
                <li><a href="#" class="pageNum">${i + 1}</a></li>
        `);
  }
  $(".page>.pagination").append(
    `<li><a href="#" class="next">&raquo;</a></li>`
  );
  $(".page>.pagination>li").eq(currentPage).addClass("active");
}

// 选择pageSize
$(".per-page").on("change", function () {
  renderTable(courseData);
});

// 点击页码切换页面
$(".page>.pagination").on("click", ".pageNum", function (event) {
  $(".pageNum").parent().removeClass("active");
  const currentPage = parseInt($(event.target).text());
  renderTable(courseData, currentPage);
  $(event.target).parent().addClass("active");
});

// 点击上下页切换页面(!!!渲染上去的，事件委托！！！)
$(".page>.pagination").on("click", ".pre", function () {
  const currentPage = parseInt($(".active>a").text());
  const prePage = currentPage - 1;
  if (currentPage === 1) {
    return;
  }
  renderTable(courseData, prePage);
});

// 点击 切换下一页
$(".page>.pagination").on("click", ".next", function () {
  const pageSize = parseInt($(".per-page").val());
  const currentPage = parseInt($(".active").text());
  const nextPage = currentPage + 1;
  const totalPages = Math.ceil(courseData.length / pageSize);
  if (currentPage === totalPages) {
    return;
  }
  renderTable(courseData, nextPage);
});

// 选择 全选
$(".table>tbody").on("change", ".select-box", function (event) {
  // 注意检验checked属性的方法
  const selected = $(event.target).prop("checked");
  const dataId = $(event.target).parent().parent().attr("data-id");
  for (let i = 0; i < courseData.length; ++i) {
    if (dataId === courseData[i].courseId) {
      courseData[i].isSelected = selected;
    }
  }
  if (selected) {
    $(event.target).parent().parent().addClass("selected-item");
  } else {
    $(event.target).parent().parent().removeClass("selected-item");
  }
});
// 全选
$(".select-all>input").on("change", function (event) {
  const currentPage = parseInt($(".active>a").text());
  const selected = $(event.target).prop("checked");
  // console.log(`selected`, selected);
  for (let i = 0; i < courseData.length; ++i) {
    courseData[i].isSelected = selected;
  }
  renderTable(courseData, currentPage);
  // if (selected) {
  //   $(".box-body>table>tbody>tr").addClass("selected-item");
  // }// 颜色换页会失效？？？

  // ？？？优化空间：全选只选单页
  // const currentPage = parseInt($(".active>a").text());
  // console.log(`currentPage`, currentPage)
  // const pageSize = parseInt($(".per-page").val());
  // console.log(`pageSize`, pageSize)
  // const startIndex = currentPage - 1;
  // console.log(`startIndex`, startIndex)
  // const endIndex = startIndex + pageSize-1;
  // console.log(`endIndex`, endIndex)
  // const selected = $(event.target).prop("checked");
  // for (let i = startIndex; i <= endIndex; ++i) {
  //   courseData[i].isSelected = selected;
  // }
  // console.log(`courseData`, courseData);
  // renderTable(courseData, currentPage);
  // if (selected) {
  //   $(".box-body>table>tbody>tr").addClass("selected-item");
  // }
});

// 搜索？？？优化空间：多个课程标题的搜索
$(".search-btn").on("click", function () {
  $(".filter-box").empty();
  const searchCourseTitle = $(".search-course-title").val().trim();
  const searchStartDate = $(".search-start-date").val();
  const searchEndDate = $(".search-end-date").val();
  let searchRes = [];
  let startRes = [];
  let endRes = [];
  if (!searchCourseTitle && !searchStartDate && !searchEndDate) {
    return;
  } else {
    if (searchCourseTitle) {
      $(".filter-box").append(
        `<div class="title-condition"><span>培训名称：</span><span class="search-title">${searchCourseTitle}</span><span class="glyphicon glyphicon-remove"></span></div>`
      );
      const searchCondition = $(".title-condition>.search-title");
      // console.log(`searchCondition.length`, searchCondition.length);
      const conditionArr = [];
      const newArr = [];
      for (let i = 0; i < searchCondition.length; ++i) {
        const conditionItem = searchCondition.eq(i).text();
        conditionArr.push(conditionItem);
      }
      // 数组去重
      arrayDeduplicate(conditionArr, newArr);
      // console.log(`conditionArr`, conditionArr);
      for (let l = 0; l < newArr.length; ++l) {
        const conditionItem = newArr[l];
        for (let j = 0; j < courseData.length; ++j) {
          const condition = courseData[j].courseTitle.includes(conditionItem);
          if (condition) {
            searchRes.push(courseData[j]);
          }
        }
      }
    }
    // 日期搜索
    if (searchStartDate || searchEndDate) {
      $(".filter-box").append(
        `<div class="time-condition"><span>培训计划时间：</span><span class="search-title">${searchStartDate}~${searchEndDate}</span><span class="glyphicon glyphicon-remove"></span></div>`
      );
      // 发布时间

      for (let i = 0; i < searchRes.length; ++i) {
        if (!searchStartDate) {
          break;
        } else {
          const condition = searchRes[i].releaseDate >= searchStartDate;
          if (!condition) {
            searchRes.splice(i, 1);
            --i;
          }
        }
      }
      // 结束时间
      for (let i = 0; i < searchRes.length; ++i) {
        if (!searchEndDate) {
          break;
        } else {
          const condition = searchRes[i].releaseDate <= searchEndDate;
          if (!condition) {
            searchRes.splice(i, 1);
            --i;
          }
        }
      }
    }
    renderTable(searchRes);
  }
});

// 重置
$(".reset-btn").on("click", function () {
  $(".filter-box").empty();
  $(".search-course-title").val("");
  $(".search-start-date").val("");
  $(".search-end-date").val("");

  renderTable(courseData);
});

// 点击删除 ==》模态框优化：点击删除跳出弹窗，点击确认后再删除(bootstrap)

// $("#courseTable>tbody").on("click", "#delConfirmBtn", function (event) {
//   // $("#delConfirmBtn").on("click", function (event) {
//   // $("#delModal").modal("hide");
//   const currentPage = parseInt($(".active").text());
//   const dataId = $(event.target).attr("data-id");
//   for (let i = 0; i < courseData.length; ++i) {
//     if (courseData[i].courseId === dataId) {
//       courseData.splice(i, 1);
//     }
//   }
//   renderTable(courseData, currentPage);
// });

// 点击删除（可以尝试放在td button后面）
// 1. 渲染 删除模态框
$(".box-body>table>tbody").on("click", ".del", function (event) {
  // 先清空上一次渲染的模态框，保持页面内始终只有1个模态框
  $("#modalBox").empty();
  const dataId = $(event.target).attr("id");
  const currentCourse = courseData.find((item) => item.courseId === dataId);
  $("#modalBox").append(`<!-- 模态框（Modal） -->
  <div
    class="modal fade"
    id="delModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="myModalLabel"
    aria-hidden="true"
    data-backdrop="static"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button
            type="button"
            class="close"
            data-dismiss="modal"
            aria-hidden="true"
          >
            &times;
          </button>
          <h4 class="modal-title" id="myModalLabel">确定要删除该课程？</h4>
        </div>
        <div class="modal-body">课程名称：${currentCourse.courseTitle}</div>
        <div class="modal-footer">
          <button 
          id="delCancelBtn"
          type="button" class="btn btn-default" data-dismiss="modal">
            取消
          </button>
          <button
            id="delConfirmBtn"
            type="button"
            class="btn btn-primary"
            data-id="${currentCourse.courseId}"
          >
            确定
          </button>
        </div>
      </div>
      <!-- /.modal-content -->
    </div>
    <!-- /.modal -->
  </div>`);
});
// 2. 删除模态框 点击确认，删除数据
$(".box-body").on("click", "#delConfirmBtn", function (event) {
  $("#delModal").modal("hide");
  const currentPage = parseInt($(".active").text());
  const dataId = $(event.target).attr("data-id");
  for (let i = 0; i < courseData.length; ++i) {
    if (courseData[i].courseId === dataId) {
      courseData.splice(i, 1);
    }
  }
  renderTable(courseData, currentPage);
});

// 点击编辑
// 1. 渲染 编辑模态框
$(".box-body>table>tbody").on("click", ".edit", function (event) {
  $("#modalBox").empty();
  const dataId = $(event.target).attr("id");
  console.log(`dataId`, dataId)
  const currentCourse = courseData.find((item) => item.courseId === dataId);
  // console.log(`currentcourse`, currentCourse);
  const isInstantRelease = currentCourse.isInstantRelease ? "checked" : "";
  const radio = currentCourse.visibleRange;
  // console.log(`radio`, radio)
  $("#modalBox").append(`    <!-- 模态框（Modal） -->
  <div
    class="modal fade"
    id="editModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="myModalLabel"
    aria-hidden="true"
    data-backdrop="static"
  >
    <div id="editArea" class="modal-dialog">
      <div id="editAreaContent" class="modal-content">
        <div id="editAreaContentBody" class="modal-body">
          <div class="edit-page">
            <div class="edit-page-box">
              <h2 id="subTitle">编辑课程</h2>
              <form class="edit-content">
      
      <!-- 课程名称 -->
      <div class="form-group edit-course-title">
        <span class="star">*</span>
        <label class="col-sm-1.5 control-label" 
          >课程名称：</label
        >
        <div class="form-group col-sm-10">
        <div class="col-sm-4">
          <input
            type="text"
            value="${currentCourse.courseTitle}"
            name="courseTitle"
            placeholder="请输入课程名称"
            class="form-control"
            id="courseTitle"
          />                    
        </div>
        <label class="control-label col-sm-7 tips" for="inputCourseTitle"></label>    </div>      
       
      </div>
      <!-- 视频封面 -->
      <div class="form-group edit-cover-image">
        <span class="star">*</span>
        <label class="col-sm-1.5 control-label" for="inputSuccess"
          >视频封面：</label
        >
        <div class="form-group col-sm-10">
        <div class="col-sm-4">
          <input
            type="file"
            value="${currentCourse.coverImage}"
            name="coverImage"
            class="form-control"
            id="coverImage"
          />
        </div>
        <label class="control-label col-sm-7 tips" for="inputCourseTitle"
        >· 支持png、jpg、jpeg等格式；大小不超过10mb</label>
        </div>
      </div>
      <!-- 课程分类 -->
      <div class="form-group edit-course-category">
        <span class="star">*</span>
        <label class="col-sm-1.5 control-label" for="inputSuccess"
          >课程分类：</label
        >
        <div class="form-group col-sm-10">
        <div class="col-sm-4">
          <select
            name=""
            id="courseCategory"
            class="form-control"
            value=""
          >
            <option value="入职培训">入职培训</option>
            <option value="办公技能培训">办公技能培训</option>
            <option value="市场培训">市场培训</option></select>
        </div>
        <label class="control-label col-sm-7 tips" for="inputCourseTitle"        
        ></label
      >
      </div>
      </div>
      <!-- 上传视频 -->
      <div class="form-group edit-video">
        <span class="star">*</span>
        <label class="col-sm-1.5 control-label" for="inputSuccess"
          >上传视频：</label
        >
        <div class="form-group col-sm-10">
        <div class="col-sm-4">
          <input
            type="file"
            value="${currentCourse.courseVideo}"
            name="courseVideo"
            class="form-control"
            id="courseVideo"
          />
        </div>
        <label class="control-label col-sm-7 tips" for="inputCourseTitle"        
        >· 支持mp4、m4v、aiv等格式；大小不超过10G</label
      ></div>
      </div>
      <!-- 课程资料 -->
      <div class="form-group edit-course-material">
        <label class="col-sm-1.5 control-label" for="inputSuccess"
          >课程资料：</label
        >
        <div class="form-group col-sm-10">
        <div class="col-sm-4">
          <input
            type="file"
            value="${currentCourse.courseMaterial}"
            name="courseMaterial"
            class="form-control"
            id="courseMaterial"
          />
        </div>
        <label class="control-label col-sm-7 tips" for="inputCourseTitle"        
        >· 支持pdf、doc、docx、exl等格式；大小不超过100mb</label
      ></div>
      </div>
      <!-- 发布时间 -->
      <div class="form-group edit-release-time">
        <label class="col-sm-1.5 control-label" for="inputSuccess"
          >发布时间：</label
        >
        <div class="col-sm-3">
          <input
            type="date"
            value="${currentCourse.releaseDate}"
            name="releaseTime"
            class="form-control"
            id="releaseDate"
          /></div>
          <div class="col-sm-3">
          <input
            type="datetime-local"
            value="${currentCourse.releaseTime}"
            name="releaseTime"
            class="form-control"
            id="releaseTime"
          /></div>
          <label class="checkbox-inline col-sm-3">
            <input
              type="checkbox"
              id="isInstantRelease"
              value="${isInstantRelease}"              
            />即时发布
          </label>
          <span class="help-block tips"></span>
        
      </div>
      <!-- 可见范围 -->
      <div class="form-group edit-visible-range">
      <label class="col-sm-1.5 control-label" for="inputSuccess"
      >可见范围：</label
    >
        <label class="radio-inline">
          <input
            type="radio"
            name="courseRange"
            id="allVisible"
            value="全部成员"
          />全部成员
        </label>
        <label class="radio-inline">
          <input
            type="radio"
            name="courseRange"
            id="designatedVisible"
            value="指定成员"
          />指定成员
        </label>        
        <button id="selectMember" class="btn btn-link select-member">选择成员</button>
        <p class="help-block col-sm-5"></p>
      </div>
      <!-- 课程简介 -->
      <div class="form-group edit-course-intro">
      <label class="col-sm-1.5 control-label" for="inputSuccess"
      >课程简介：</label>
      <div class="col-sm-8 textarea-box">
        <img 
          src="https://cdn3.axureshop.com/demo/2080033/images/%E6%96%B0%E5%A2%9E%E8%81%8C%E4%BD%8D_1/u8031.png"
        />
        <textarea
          name=""
          id="courseIntro"
          value="${currentCourse.courseIntro}"
          cols="30"
          rows="10"
          class="form-control"
        ></textarea>
        </div>
      </div>
    </form>

            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">
            取消
          </button>
          <button
            id="editConfirmBtn"
            type="button"
            class="btn btn-primary"
            data-id="${currentCourse.courseId}"
          >
            确定
          </button>
        </div>
      </div>
      <!-- /.modal-content -->
    </div>
    <!-- /.modal -->
  </div>`);
  // 单选框赋值
  const isChecked = currentCourse.visibleRange === "全部成员" ? "checked" : "";
  $("#allVisible").attr("checked", isChecked);
  $("#designatedVisible").attr("checked", !isChecked);
  // 下拉框赋值
  $("#courseCategory ").val(currentCourse.courseCategory);
  // $("#courseCategory option:selected").val(currentCourse.courseCategory)
});
// 点击 选择成员

// $("#modalBox").on("click", "#selectMember", function () {
//   console.log("test1");
//   $("#editModal").modal("hide");
//   console.log(`test2`);
//   // $("#innerModalBox").append(`<!-- 模态框（Modal） -->
//   // <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
//   //     <div class="modal-dialog">
//   //         <div class="modal-content">
//   //             <div class="modal-header">
//   //                 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
//   //                 <h4 class="modal-title" id="myModalLabel">选择成员</h4>
//   //             </div>
//   //             <div class="modal-body">选择成员</div>
//   //             <div class="modal-footer">
//   //                 <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
//   //                 <button type="button" class="btn btn-primary">提交更改</button>
//   //             </div>
//   //         </div><!-- /.modal-content -->
//   //     </div><!-- /.modal -->
//   // </div>
//   // `);
//   $("#myModal").show();
//   console.log("test3");
// });
formValidation();
// 2. 编辑模态框：点击确认==》填入内容==（修改）==》信息验证==》保存数据
$(".box-body").on("click", "#editConfirmBtn", function (event) {
  const currentPage = parseInt($(".active").text());
  const dataId = $(event.target).attr("data-id");  
  // 验证
  formValidation();
  const currentCourse = courseData.find((item) => item.courseId === dataId);
  const eqLength = $(".edit-content>div>.col-sm-10").length;
  const testList = $(".edit-content>div>.col-sm-10");
  for (let i = 0; i < eqLength; ++i) {
    const condition = testList.eq(i).attr("class").includes("has-error");
    if (condition) {
      return;
    } else {
      currentCourse.courseTitle = $("#courseTitle").val();
      currentCourse.coverImage = $("#coverImage").val();
      currentCourse.courseCategory = $("#courseCategory").val();
      currentCourse.courseVideo = $("#courseVideo").val();
      currentCourse.courseMaterial = $("#courseMaterial").val();
      currentCourse.releaseDate = $("#releaseDate").val();
      currentCourse.releaseTime = $("#releaseTime").val();
      currentCourse.updateDate = formatDate(new Date());
      currentCourse.isInstantRelease =
        $("#isInstantRelease").val() === "checked";
      // 可见范围

      currentCourse.visibleRange = $(
        ':radio[name="courseRange"]:checked'
      ).val();
      currentCourse.courseIntro = $("#courseIntro").val();
      $("#editModal").modal("hide");
      // .push({
      //   courseId: `${createId()}`,
      //   isSelected: false,
      //   // coverImage:
      //   //   `${}`,
      //   courseTitle: "2022新员工入职",
      //   courseType: "视频",
      //   courseVideo: "",
      //   courseMaterial: "",
      //   courseCategory: "入职培训",
      //   visibleRange: "指定成员",
      //   numOfStudents: 11,
      //   releaseDate: "2022-01-03",
      //   releaseTime: "",
      //   updateDate: "2022-01-04",
      //   courseIntro: "",
      // });
    }
  }
  console.log(`courseData`, courseData);
  renderTable(courseData, currentPage);
});

// 点击 新增课程
// 1. 渲染 新增模态框
$(".add-btn").on("click", function (event) {
  $("#modalBox").empty();
  $("#modalBox").append(`    <!-- 模态框（Modal） -->
  <div
    class="modal fade"
    id="addModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="myModalLabel"
    aria-hidden="true"
    data-backdrop="static"
  >
    <div id="editArea" class="modal-dialog">
      <div id="editAreaContent" class="modal-content">
      <div class="modal-header">
      <button
        type="button"
        class="close"
        data-dismiss="modal"
        aria-hidden="true"
      >
        &times;
      </button>
      <h4 class="modal-title" id="myModalLabel"></h4>
    </div>
        <div id="editAreaContentBody" class="modal-body">
          <div class="edit-page">     
            <div class="edit-page-box">
              <h2 id="subTitle">新增课程</h2>
              <form class="edit-content">

      <!-- 课程名称 -->
      <div class="form-group edit-course-title">
        <span class="star">*</span>
        <label class="col-sm-1.5 control-label"
          >课程名称：</label
        >
        <div class="form-group col-sm-10">
        <div class="col-sm-4">
          <input
            type="text"
            value=""
            name="courseTitle"
            placeholder="请输入课程名称"
            class="form-control"
            id="courseTitle"
          />
        </div>
        <label class="control-label col-sm-7 tips" for="inputCourseTitle"></label>    </div>

      </div>
      <!-- 视频封面 -->
      <div class="form-group edit-cover-image">
        <span class="star">*</span>
        <label class="col-sm-1.5 control-label" for="inputSuccess"
          >视频封面：</label
        >
        <div class="form-group col-sm-10">
        <div class="col-sm-4">
          <input
            type="file"
            value=""
            name="coverImage"
            class="form-control"
            id="coverImage"
          />
        </div>
        <label class="control-label col-sm-7 tips" for="inputCourseTitle"
        >· 支持png、jpg、jpeg等格式；大小不超过10mb</label>
        </div>
      </div>
      <!-- 课程分类 -->
      <div class="form-group edit-course-category">
        <span class="star">*</span>
        <label class="col-sm-1.5 control-label" for="inputSuccess"
          >课程分类：</label
        >
        <div class="form-group col-sm-10">
        <div class="col-sm-4">
          <select
            name=""
            id="courseCategory"
            class="form-control"
            value=""
          >
            <option value="入职培训" selected>入职培训</option>
            <option value="办公技能培训">办公技能培训</option>
            <option value="市场培训" >市场培训</option></select>
        </div>
        <label class="control-label col-sm-7 tips" for="inputCourseTitle"
        ></label
      >
      </div>
      </div>
      <!-- 上传视频 -->
      <div class="form-group edit-video">
        <span class="star">*</span>
        <label class="col-sm-1.5 control-label" for="inputSuccess"
          >上传视频：</label
        >
        <div class="form-group col-sm-10">
        <div class="col-sm-4">
          <input
            type="file"
            value=""
            name="courseVideo"
            class="form-control"
            id="courseVideo"
          />
        </div>
        <label class="control-label col-sm-7 tips" for="inputCourseTitle"
        >· 支持mp4、m4v、aiv等格式；大小不超过10G</label
      ></div>
      </div>
      <!-- 课程资料 -->
      <div class="form-group edit-course-material">
        <label class="col-sm-1.5 control-label" for="inputSuccess"
          >课程资料：</label
        >
        <div class="form-group col-sm-10">
        <div class="col-sm-4">
          <input
            type="file"
            value=""
            name="courseMaterial"
            class="form-control"
            id="courseMaterial"
          />
        </div>
        <label class="control-label col-sm-7 tips" for="inputCourseTitle"
        >· 支持pdf、doc、docx、exl等格式；大小不超过100mb</label
      ></div>
      </div>
      <!-- 发布时间 -->
      <div class="form-group edit-release-time">
        <label class="col-sm-1.5 control-label" for="inputSuccess"
          >发布时间：</label
        >
        <div class="col-sm-3">
          <input
            type="date"
            value=""
            name="releaseTime"
            class="form-control"
            id="releaseDate"
          /></div>
          <div class="col-sm-3">
          <input
            type="datetime-local"
            value=""
            name="releaseTime"
            class="form-control"
            id="releaseTime"
          /></div>
          <label class="checkbox-inline col-sm-3">
            <input
              type="checkbox"
              id="isInstantRelease"
              value=""
            />即时发布
          </label>
          <span class="help-block tips"></span>

      </div>
      <!-- 可见范围 -->
      <div class="form-group edit-visible-range">
      <label class="col-sm-1.5 control-label" for="inputSuccess"
      >可见范围：</label
    >
        <label class="radio-inline">
          <input
            type="radio"
            name="range"
            id="allVisible"
            value="全部成员"

          />全部成员
        </label>
        <label class="radio-inline">
          <input
            type="radio"
            name="range"
            id="designatedVisible"
            value="指定成员"
            checked
          />指定成员
        </label>
        <button id="selectMember" class="btn btn-link select-member" data-toggle="modal" data-target="#myModal">选择成员</button>
        <p class="help-block col-sm-5"></p>
      </div>
      <!-- 课程简介 -->
      <div class="form-group edit-course-intro">
      <label class="col-sm-1.5 control-label" for="inputSuccess"
      >课程简介：</label>
      <div class="col-sm-8 textarea-box">
        <img
          src="https://cdn3.axureshop.com/demo/2080033/images/%E6%96%B0%E5%A2%9E%E8%81%8C%E4%BD%8D_1/u8031.png"
        />
        <textarea
          name=""
          id="courseIntro"
          value=""
          cols="30"
          rows="10"
          class="form-control"
        ></textarea>
        </div>
      </div>
    </form>

            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">
            取消
          </button>
          <button
            id="addConfirmBtn"
            type="button"
            class="btn btn-primary"
            data-id=""
          >
            确定
          </button>
        </div>
      </div>
      <!-- /.modal-content -->
    </div>
    <!-- /.modal -->
  </div>`);
});

// 点击 选择成员
// $("#modalBox").on("click", "#selectMember", function (event) {
//   // $("#innerModalBox").empty();
//   console.log("test");
//   $("#innerModalBox").append(`<div>123</div>`)
// $("#innerModalBox").append(`<!-- 模态框（Modal） -->
// <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
//     <div class="modal-dialog">
//         <div class="modal-content">
//             <div class="modal-header">
//                 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
//                 <h4 class="modal-title" id="myModalLabel">选择成员</h4>
//             </div>
//             <div class="modal-body">选择成员</div>
//             <div class="modal-footer">
//                 <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
//                 <button type="button" class="btn btn-primary">提交更改</button>
//             </div>
//         </div><!-- /.modal-content -->
//     </div><!-- /.modal -->
// </div>
// `);
// });

// 2. 新增模态框：点击确认==》填入内容==（修改）==》信息验证==》保存数据
$(".box-body").on("click", "#addConfirmBtn", function (event) {
  const currentPage = parseInt($(".active").text());
  // 验证
  formValidation();
  const eqLength = $(".edit-content>div>.col-sm-10").length;
  const testList = $(".edit-content>div>.col-sm-10");
  // 必填项 非空
  for (let i = 0; i < 3; ++i) {
    const conditionNull = $(".edit-content>div>.col-sm-10>.col-sm-4>input")
      .eq(i)
      .val();
    if (!conditionNull) {
      return;
    }
  }
  // 提示框中无has-error
  for (let i = 0; i < eqLength; ++i) {
    const condition = testList.eq(i).attr("class").includes("has-error");
    if (condition) {
      return;
    }
  }
  $("#addModal").modal("hide");
  // 下拉框值
  const option = $("#courseCategory option:selected").val();
  // console.log(`option`, option);
  // ？？？单选框值
  const radio = $(':radio[name="range"]:checked').val();
  // console.log(`radio`, radio);

  const addCourse = {
    courseId: `${createId()}`,
    isSelected: false,
    coverImage: $("#coverImage").val(),
    courseTitle: $("#courseTitle").val(),
    courseType: "视频",
    courseVideo: $("#courseVideo").val(),
    courseCategory: `${option}`,
    visibleRange: radio,
    numOfStudents: "",
    releaseDate: $("#releaseDate").val(),
    updateDate: formatDate(new Date()),
    isInstantRelease: $("#isInstantRelease").val() === "checked",
    // 可见范围
    // courseData[index].visibleRange = ;
    courseIntro: $("#courseIntro").val(),
  };
  courseData.push(addCourse);
  // console.log(`courseData`, courseData);
  renderTable(courseData, currentPage);
});

/* 
  编辑页，点击 确认
  1. 校验信息
  2. 保存信息
  3. 渲染table
*/
function formValidation() {
  // 验证 1. courseTitle
  $("#modalBox").on(
    "blur",
    ".edit-course-title>div>div>input",
    function (event) {
      const value = $(event.target).val().trim();
      const name = $(event.target).attr("name");
      const rule = rules[name].contentReg;
      const contentErrorMessage = rules[name].contentErrorMessage;
      if (!rule.test(value)) {
        $(event.target).parent().next().text("");
        $(event.target).parent().parent().removeClass("has-error");
        $(event.target).parent().parent().addClass("has-success");
      } else {
        $(event.target).parent().next().text(`${contentErrorMessage}`);
        $(event.target).parent().parent().removeClass("has-success");
        $(event.target).parent().parent().addClass("has-error");
        return;
      }
    }
  );
  // 验证 2. coverImage
  $("#modalBox").on(
    "change",
    ".edit-cover-image>div>div>input",
    function (event) {
      $(event.target).next().text("");
      const value = $(event.target).val();
      const name = $(event.target).attr("name");
      // 类型验证
      const rule = rules[name].contentReg;
      const contentErrorMessage = rules[name].contentErrorMessage;
      const tips = rules[name].tips;
      if (!value) {
        $(event.target).parent().next().text("");
        $(event.target).parent().next().text(`${tips}`);
        $(event.target).parent().parent().addClass("has-error");
        return;
      } else if (rule.test(value)) {
        $(event.target).parent().next().text("");
        $(event.target).parent().parent().removeClass("has-error");
        $(event.target).parent().parent().addClass("has-success");
      } else {
        $(event.target).parent().next().text("");
        $(event.target).parent().next().text(`${contentErrorMessage}`);
        $(event.target).parent().parent().removeClass("has-success");
        $(event.target).parent().parent().addClass("has-error");
        return;
      }
    }
  );

  // 验证 3. courseCategory

  // 验证 4. courseVideo
  $("#modalBox").on("change", ".edit-video>div>div>input", function (event) {
    $(event.target).next().text("");
    const value = $(event.target).val();
    const name = $(event.target).attr("name");
    // 类型验证
    const rule = rules[name].contentReg;
    const contentErrorMessage = rules[name].contentErrorMessage;
    const tips = rules[name].tips;
    if (!value) {
      $(event.target).parent().next().text("");
      $(event.target).parent().next().text(`${tips}`);
      $(event.target).parent().parent().addClass("has-error");
      return;
    } else if (rule.test(value)) {
      $(event.target).parent().next().text("");
      $(event.target).parent().parent().removeClass("has-error");
      $(event.target).parent().parent().addClass("has-success");
    } else {
      $(event.target).parent().next().text("");
      $(event.target).parent().next().text(`${contentErrorMessage}`);
      $(event.target).parent().parent().removeClass("has-success");
      $(event.target).parent().parent().addClass("has-error");
      return;
    }
  });

  // 验证 5. courseMaterial
  $("#modalBox").on(
    "change",
    ".edit-course-material>div>div>input",
    function (event) {
      $(event.target).next().text("");
      const value = $(event.target).val();
      const name = $(event.target).attr("name");
      // 类型验证
      const rule = rules[name].contentReg;
      const contentErrorMessage = rules[name].contentErrorMessage;
      const tips = rules[name].tips;
      if (!value) {
        $(event.target).parent().next().text("");
        $(event.target).parent().next().text(`${tips}`);
        $(event.target).parent().parent().removeClass("has-error");
        return;
      } else if (rule.test(value)) {
        $(event.target).parent().next().text("");
        $(event.target).parent().parent().removeClass("has-error");
        $(event.target).parent().parent().addClass("has-success");
      } else {
        $(event.target).parent().next().text("");
        $(event.target).parent().next().text(`${contentErrorMessage}`);
        $(event.target).parent().parent().removeClass("has-success");
        $(event.target).parent().parent().addClass("has-error");
        return;
      }
    }
  );

  // 表单验证：？？？优化：封装
}
// function check(target) {
//   //
// }

// 点击 提交按钮

$(".submit-btn").on("click", function () {
  // 1. 检测必填项：
  const classList = $(".edit-content .tips").attr("class");
  // console.log(`classList`, classList);
});

// let index = 100;
// function createId() {
//   return ++index;
// }
// const inputs=$(".edit-content input")
// console.log(`inputs`, inputs)

//补0函数
function getZeroPadding(num) {
  return num < 10 ? `0${num}` : num;
}
//格式化时间:
function formatDate(date) {
  let year = date.getFullYear();
  //月份+1，<10 补0
  let month = getZeroPadding(date.getMonth() + 1);
  //日期补0
  let day = getZeroPadding(date.getDate());
  //小时补0
  let hours = getZeroPadding(date.getHours());
  //分钟补0
  let minutes = getZeroPadding(date.getMinutes());
  //秒补0
  let seconds = getZeroPadding(date.getSeconds());
  return `${year}-${month}-${day}`;
}
// 数组去重
function arrayDeduplicate(arr, newArr) {
  const obj = {};
  for (let i = 0; i < arr.length; ++i) {
    const key = arr[i]; //遍历数组valueArr，将每个值作为obj 的key 值
    obj[key] = 1; //每个key 的value 赋1
  }
  for (let key in obj) {
    newArr.push(key); //遍历obj
  }
}
